package org.jeecg.modules.demo.crm.util.execl;

import com.aspose.cells.PdfSaveOptions;
import com.aspose.cells.Workbook;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.Base64;

public class AsposeCellsUtil {


    /**
     * Excel 转 PDF 工具方法
     * @param excelFilePath 输入 Excel 文件路径
     * @param pdfFilePath 输出 PDF 文件路径
     * @throws Exception 转换异常时抛出
     */
    public static void excelToPdf(String excelFilePath, String pdfFilePath) throws Exception {
        // 加载 Excel 文件
        Workbook workbook = new Workbook(excelFilePath);

        // PDF保存选项（可自定义）
        PdfSaveOptions options = new PdfSaveOptions();
        options.setAllColumnsInOnePagePerSheet(true); // 所有列缩放到一页

        // 执行转换，保存PDF
        workbook.save(pdfFilePath, options);
    }

    /**
     * pdf 转图片
     * @param pdfPath
     * @return
     * @throws Exception
     */

    public static String convertFirstPageToBase64(String pdfPath) throws Exception {
        try (PDDocument document = PDDocument.load(new File(pdfPath))) {
            PDFRenderer renderer = new PDFRenderer(document);
            BufferedImage raw = renderer.renderImageWithDPI(0, 150);

            // 1. 先去掉顶部 30 px
            final int cropTop = 30;
            BufferedImage noTop = raw.getSubimage(0, cropTop,
                    raw.getWidth(), raw.getHeight() - cropTop);

            // 2. 再去掉四周空白
            BufferedImage trimmed = trimBlank(noTop);

            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ImageIO.write(trimmed, "PNG", os);
            return "<img src=\"data:image/png;base64," + Base64.getEncoder().encodeToString(os.toByteArray())+ "\"/>";
        }
    }

    /** 返回裁剪掉四周空白后的图像 */
    public static BufferedImage trimBlank(BufferedImage img) {
        final int width  = img.getWidth();
        final int height = img.getHeight();

        int top    = 0;
        int bottom = height - 1;
        int left   = 0;
        int right  = width - 1;

        int whiteRGB = 0xFFFFFFFF;          // 纯白
        double tolerance = 0.98;            // 95% 像素为白即认为整行/列是空白

        // 找上边界
        while (top <= bottom && isBlankHorizontal(img, top, whiteRGB, tolerance)) top++;
        // 找下边界
        while (bottom >= top && isBlankHorizontal(img, bottom, whiteRGB, tolerance)) bottom--;

        /* ---------- 新增：下边界保留 20 px 高度 ---------- */
        bottom = Math.max(bottom, top - 1 + 20);   // 至少留 20 行，且不超过原图范围

        // 找左边界
        while (left <= right && isBlankVertical(img, left, whiteRGB, tolerance)) left++;
        // 找右边界
        while (right >= left && isBlankVertical(img, right, whiteRGB, tolerance)) right--;

        if (top > bottom || left > right) {
            // 全白，返回原图
            return img;
        }
        return img.getSubimage(left, top, right - left + 1, bottom - top + 1);
    }

    private static boolean isBlankHorizontal(BufferedImage img, int y, int whiteRGB, double tolerance) {
        int white = 0;
        for (int x = 0; x < img.getWidth(); x++) {
            if ((img.getRGB(x, y) & 0xFFFFFF) == (whiteRGB & 0xFFFFFF)) white++;
        }
        return white >= img.getWidth() * tolerance;
    }

    private static boolean isBlankVertical(BufferedImage img, int x, int whiteRGB, double tolerance) {
        int white = 0;
        for (int y = 0; y < img.getHeight(); y++) {
            if ((img.getRGB(x, y) & 0xFFFFFF) == (whiteRGB & 0xFFFFFF)) white++;
        }
        return white >= img.getHeight() * tolerance;
    }

}
